<?php

namespace App\Models\user;

use App\Api\Models\Member;
use App\Api\Services\Token;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class UserToken extends Model
{
    use HasFactory;
    protected $guarded =[];
    protected $table ='cmc_user_token';

    /**
     * 创建token并且保存
     * @param Member $user
     * @param $type
     * @return UserToken
     */
    public static function createToken(Member $user, $type): self
    {
        $tokenInfo = $user->getToken($type);
        $tokenInfo = Token::MakeToken();
        return self::create([
            'member_id' => $user->member_id,
            'token' => $tokenInfo['token'],
            'expires_time' => date('Y-m-d H:i:s', $tokenInfo['params']['exp'])
        ]);
    }

    /**
     * 删除一天前的过期token
     * @return bool
     * @throws \Exception
     */
    public static function delToken()
    {
        return self::where('expires_time', '<', date('Y-m-d H:i:s',strtotime('-1 day')))->delete();
    }

}
